import { FC, useState } from 'react'
import { Button, Input, message } from 'antd'
import './index.scss'
import { LOGIN_USER, setLSData } from '../../logic/handleLS'
import { request } from '../../logic/request'

interface Props {
  onSuccess: (username: string) => void
}

// 登录页面
const Login: FC<Props> = (props) => {
  const { onSuccess } = props
  const [username, setUsername] = useState('')

  function handleNameChange(event: any) {
    const { value } = event.target
    setUsername(value)
  }

  function handleSubmit() {
    // 校验用户名
    if (!username.trim()) {
      message.error('我劝你明智点，老实点填写用户名!')
      return
    }
    // 发起接口请求，然后切换页面信息
    request(
      {
        url: '/loginUser',
        method: 'post',
        data: {
          username
        }
      },
      true
    )
      .then((res: any) => {
        if (!res || !res.success) {
          message.error(res?.message || '登录失败!')
          return
        }
        message.success('验证成功！')
        setLSData(LOGIN_USER, username)
        // 发起接口请求，然后切换页面信息
        onSuccess(username)
      })
      .catch((rej) => {
        console.error('rej', rej)
      })
  }

  return (
    <div className="login">
      <div className="loginForm">
        <Input
          className="loginForm__input"
          onChange={handleNameChange}
          value={username}
          onPressEnter={handleSubmit}
          placeholder="Your name"
        />
        <Button onClick={handleSubmit}>登录</Button>
      </div>
    </div>
  )
}

export default Login
